#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 基于python 实现
# 运行命令 python addChange.py 渠道号 apk包
# python addChange.py 40305144046 E:\需求\大屏\验收\江西渠道-计费版\migujianshen-TV1.1.2-176-jiangxi.apk
# 程序 脚本 渠道号 直接将apk包拖入
import os
import sys
import zipfile

import shutil
import fileUtils
import platform
import xmlHelper

# 获取当前py文件所在的目录
py_home = os.path.dirname(os.path.realpath(sys.argv[0]))
print("py_home = " + py_home)

source_folder = py_home + os.sep + "origin_apk"
fileUtils.mkdir(source_folder)
source_file = ""
source_files = os.listdir(source_folder)
if len(source_files) == 0:
    print("请在origin_apk目录存放apk")
    sys.exit(0)
elif len(source_files) > 1:
    print("请在origin_apk目录中只存放一个apk")
    sys.exit(0)
else:
    source_file = source_folder + os.sep + source_files[0]

full_file_name = os.path.splitext(source_file)[0]
split = full_file_name.split(os.sep)
file_name = split[len(split) - 1]
print("source_file = " + source_file)
print("full_file_name = " + full_file_name)
print("file_name = " + file_name)
# 获取渠道号
# 获取渠道文件路径
channel_file_path = py_home + os.sep + 'UMENG_CHANNEL_NUM.txt'
manifest_folder_ = py_home + os.sep + "sf_folder"
if not os.path.exists(manifest_folder_):
    os.mkdir(manifest_folder_)
# 写入的渠道配置文件名称&节点名
channel_file_name = "channel.xml"
channel_apk_folder = "channel_apk"
channel_apk_home = py_home + os.sep + channel_apk_folder
tagName = 'channel_id'
keystore = py_home + os.sep + "shanpaosign.keystore"
print("keystore路径 = " + keystore + " 是否存在 = " + str(os.path.exists(keystore)))
if not os.path.exists(keystore):
    print("请先放入keystore")
    sys.exit(0)
# 读取渠道list文档，存入list
sf_name = "SHANPAO.SF"
temp_ = py_home + os.sep + "temp"

fileUtils.delete_folder(channel_apk_home)
fileUtils.mkdir(channel_apk_home)
fileUtils.delete_folder(manifest_folder_)
fileUtils.mkdir(manifest_folder_)
fileUtils.delete_folder(temp_)
fileUtils.mkdir(temp_)
target_apk_folder = "target_apk"
fileUtils.delete_folder(target_apk_folder)
fileUtils.delete_folder("rsa_temp")
# sys.exit(0)
with open(channel_file_path, "tr", encoding="utf-8") as f:  # 打开文件
    # 按行读取文件
    channel_list = f.readlines()
    print(channel_list)
    successCount = 0

    for line in channel_list:
        line = line.strip('\n')  # 去掉列表中每一个元素的换行符
        channel_id = line.split("##")
        channel_name = channel_id[1]
        channel_code = channel_id[0]
        print(channel_name)

        new_apk_file = channel_apk_home + os.sep + channel_code + ".apk"
        if os.path.exists(new_apk_file):
            print("旧渠道文件已存在，正在删除")
            os.remove(new_apk_file)

        print("渠道apk路径: " + new_apk_file)
        # 复制apk包，去除META-INF目录
        print("正在生成渠道apk")
        originZip = zipfile.ZipFile(source_file, 'r')
        out_zip = zipfile.ZipFile(new_apk_file, 'w')
        for item in originZip.infolist():
            buffer = originZip.read(item.filename)
            if "channel.xml" in item.filename:
                print(item.filename + "源文件包含渠道文件,删除渠道文件")
                continue
            elif "META-INF" in item.filename:
                print(item.filename + "源文件包含META-INF,删除META-INF")
                continue
            else:
                out_zip.writestr(item, buffer)
        out_zip.close()
        originZip.close()
        print("渠道apk生成成功")
        fileUtils.delete_file(str(originZip))
        # 写入渠道文件
        try:
            zip = zipfile.ZipFile(new_apk_file, 'a', zipfile.ZIP_DEFLATED)
            print(zip.filename)
            print("准备写入渠道文件")
            # 生成渠道xml文件
            xmlHelper.write_channel_xml(channel_file_name, tagName, channel_code)
            print("文件名：" + full_file_name)
            info = zip.NameToInfo.get("assets" + os.sep + channel_file_name)
            if info is None:
                print("正在写入" + channel_file_name)
                zip.write(channel_file_name, "assets" + os.sep + channel_file_name)
                zip.close()
        except BaseException as e:
            print(e)
            print("写入渠道文件出错")

        print(channel_name + "正在签名 ")
        apksigncmd = "jarsigner -sigalg SHA1withRSA -digestalg SHA1 -keystore " + keystore + " -storepass android -keypass android " + new_apk_file + " shanpao "
        os.system(apksigncmd)
        print(channel_name + "签名成功 ")
        try:
            print("正在读取sf文件")
            zip = zipfile.ZipFile(new_apk_file, 'a', zipfile.ZIP_DEFLATED)

            extract = zip.extract("META-INF" + os.sep + sf_name, temp_)
            shutil.move(temp_ + os.sep + "META-INF" + os.sep + sf_name,
                        manifest_folder_ + os.sep + channel_code + "_" + sf_name)  # 移动
            print("提取sf文件成功 已将" + channel_name + "放到manifest_folder_目录下")
            print(channel_name + "------ok")
            successCount = successCount + 1
            print("已完成, 输出" + str(successCount) + "个文件")
        except BaseException as e:
            print("提取sf文件出错 文件名：" + new_apk_file)
            print(e)
listdir = os.listdir(manifest_folder_)
print("正在打包sf文件")
sf_zip = zipfile.ZipFile(manifest_folder_ + os.sep + "sf.zip", 'a', zipfile.ZIP_DEFLATED)
for sf in listdir:
    print(sf)
    sf_zip.write(manifest_folder_ + os.sep + sf, sf)
sf_zip.close()
print("sf文件打包成功，请提取sf.zip上传到管理后台生成签名文件")
fileUtils.open_path(manifest_folder_)
